export enum EnumSportsOddsType {
  /** 小数式、欧洲  */
  DECIMAL = 'DECIMAL',
  /** 美式 */
  AMERICAN = 'AMERICAN',
  /** 香港格式 */
  HONGKONG = 'HONGKONG',
  /** 印尼格式 */
  INDONESIA = 'INDONESIA',
  /** 马来格式 */
  MALAYSIA = 'MALAYSIA',
  /** 分数式 */
  FRACTION = 'FRACTION',
}
export enum EPageDataMarketType {
  /** 赛事 */
  EVENT = 'event',
  /** 冠军 */
  OUTRIGHT = 'outright'
}

export enum EnumSportsEventType {
  /** 今日赛事 */
  TODAY = 1,
  /** 滚球 */
  LIVE = 2,
  /** 早盘 */
  EARLY = 3,
  /** 串关 */
  CHUAN = 4,
  /** 冠军 */
  OUTRIGHT = 5,
  /** 热门赛事 */
  HOT = 6,
}

/** 投注单数据格式 */
interface IBetSlipData {
  // 测试
  [key: string]: any
}

export const useSportsStore = defineStore('sports', () => {
  const { t } = useI18n()
  const router = useRouter()
  const { isLogin, currentGlobalCurrency } = storeToRefs(useAppStore())
  const { userInfo, rebateAutomatic } = storeToRefs(useAppStore())

  /** 体育赔率展示方式 */
  const sportsOddsType = ref(getSportsOddsType())
  /** 投注单数据 */
  const betSlipData = ref<IBetSlipData[]>([])
  /** 当前场馆ID */
  const currentProvider = ref(Local.get<string>(STORAGE_SPORTS_CURRENT_PROVIDER)?.value ?? '')
  /** 滚球当前球种 */
  const currentLiveNav = ref(-1)
  /** 即将开赛当前球种 */
  const currentUpcomingNav = ref(0)
  /** 虚拟体育当前球种 */
  const currentVSportsNav = ref(-1)
  /** 虚拟体育当前盘口类型 */
  const currentVSportsBetType = ref('')
  /** 购物车 */
  const cart = reactive(new SportsCart(currentGlobalCurrency.value))
  /** 体育场馆登录成功 */
  const { bool: isSportsLoginSusses } = useBoolean(false)
  /** 本次是否请求过数据 */
  const { bool: isSportsLogin, setBool: setSportLogin } = useBoolean(false)
  /** 体育场馆维护 */
  const isSportsMaintained = ref(globalInitMap.isSportsMaintained)
  /** 是否展示所有球种列表 */
  const isShowAllSportsList = ref(false)
  /** 是否切换快速投注 */
  const isOnSportsQuickBet = ref(false)
  /** 热门当前球种 */
  const currentHotNav = ref(-1)
  /** 早盘当前球种 */
  const currentEarlyNav = ref(-1)

  /**
   * 是否请求体育登录接口
   *
   * 比如在体育路由下面，并且是登录状态
   */
  const isRequestSportsLogin = computed(() => {
    // 本次项目是否请求过体育登录接口
    const isSportPath = router.currentRoute.value.path.includes('sports')
    let status = false
    if (isSportsLogin.value)
      status = false

    if (isLogin.value && isSportPath && !isSportsLogin.value) {
      status = true
      setSportLogin(true)
    }
    return status
  })

  /** 体育计数源 */
  const { data: allSportsCount, run: runSportsCount } = useRequest(() =>
    ApiSportCount({ ic: 0 }),
    {
      onSuccess(res) {
        // 统一加载icon
        res.list.forEach((a) => {
          application.loadImage(a.spic)
        })

        // 热门
        const hostArr = res.list.filter(a => a.ohc > 0)
        if (hostArr.length > 0) {
          if (currentHotNav.value === -1)
            currentHotNav.value = hostArr[0].si

          else if (!hostArr.find(a => a.si === currentHotNav.value))
            currentHotNav.value = hostArr[0].si
        }
        else {
          currentHotNav.value = 1
        }

        // 滚球
        const liveArr = res.list.filter(a => a.lc > 0)
        if (liveArr.length > 0) {
          if (currentLiveNav.value === -1)
            currentLiveNav.value = liveArr[0].si

          else if (!liveArr.find(a => a.si === currentLiveNav.value))
            currentLiveNav.value = liveArr[0].si
        }
        else {
          currentLiveNav.value = 1
        }

        // 早盘
        const earlyArr = res.list.filter(a => a.ec > 0)
        if (earlyArr.length > 0) {
          if (currentEarlyNav.value === -1)
            currentEarlyNav.value = earlyArr[0].si

          else if (!earlyArr.find(a => a.si === currentEarlyNav.value))
            currentEarlyNav.value = earlyArr[0].si
        }
        else {
          currentEarlyNav.value = 1
        }
      },
    })

  /** 赛事收藏数据源 */
  const {
    data: sportsFavoriteData,
    run: runGetFavoriteList,
  } = useRequest(ApiSportGetFavoriteList, {
    throttleInterval: 1500,
  })

  /** 体育场馆登录 */
  const { run: runAsyncSportsLogin } = useRequest(() => ApiSportsLogin({ cur: currencyConfig[currentGlobalCurrency.value].cur }), {
    errorRetryCount: 3,
    errorRetryInterval: 1000,
    refreshDeps: [currentGlobalCurrency, isLogin],
    refreshDepsAction: () => {
      if (isRequestSportsLogin.value)
        runAsyncSportsLogin()
    },
    onSuccess() {
      isSportsLoginSusses.value = true
      runGetFavoriteList({
        si: 0,
        cur: currencyConfig[currentGlobalCurrency.value].cur,
      })
    },
  })

  /** 侧边栏数据源 */
  const { data: sidebarData, run: runSportsSidebar } = useRequest(ApiSportSidebar, {
    onSuccess() {
      if (isRequestSportsLogin.value)
        runAsyncSportsLogin()
    },
  })

  /** 所有地区联赛数据 */
  const {
    data: competitionListData,
    run: runGetCompetitionListData,
    runAsync: runAsyncGetCompetitionListData
  } = useRequest(ApiSportCompetitionList)

  /** 首页相关设定 */
  const { data: homePageConfig, runAsync: runAsyncHomeConfig } = useRequest(ApiSportsHomePageConfig, {
    onSuccess(res) {
      if (res.list_filter) {
        // 统一加载icon
        res.list_filter.forEach((a) => {
          application.loadImage(a.icon)
          application.loadImage(a.icon_hl)
        })
      }
    },
  })

  function init() {
    currentProvider.value = '401'
    Local.set(STORAGE_SPORTS_CURRENT_PROVIDER, currentProvider.value)
    runAsyncHomeConfig().then(() => runSportsCount())
    runSportsSidebar()
  }
  init()

  const AllOddsTypes = computed<Array<{
    label: string
    value: EnumSportsOddsType
  }>>(() => Object.values(EnumSportsOddsType).map(m => ({ label: t(m), value: m })))

  /** 滚球计数 */
  const liveCount = computed(() => {
    if (allSportsCount.value) {
      return allSportsCount.value.list.reduce((acc, cur) => {
        return acc + cur.lc
      }, 0)
    }
    return 0
  })

  /** 侧边栏菜单 */
  const sportsMenu = computed(() => {
    return [
      {
        title: t('h5_sports_pop_up_menu_live_events'),
        path: getSportsRoutePath({ page: '/live' }),
        icon: 'sports-live',
        list: [],
        domId: '',
        fixtureCount: liveCount.value,
      },
      {
        title: t('sports_left_side_menu_my_bets'),
        path: getSportsRoutePath({ page: '/bets' }),
        icon: 'menu-my-bet',
        list: [],
        domId: '',
        token: true,
        sptToken: true,
      },
      isLogin.value && rebateAutomatic.value && +rebateAutomatic.value.automatic === 3 && userInfo.value && +userInfo.value.rebate_state && +userInfo.value.bonus_state === 1
        ? {
          domId: 'realTimeRebateDomId',
          path: '',
          list: [],
          token: true,
          icon: 'menu-rebate',
          title: t('vip_rebate_center'),
          callBack: () => {
            console.log("🚸🚸🚸 ~ sportsMenu ~ 打开即时返水弹窗:",)
            // openRealTimeRebateDialog()
          },
        }
        : undefined,
    ].filter(m => !!m)
  })

  /** 顶级体育项目 */
  const sportHotGames = computed<Menu>(() => {
    if (sidebarData.value && sidebarData.value.menu) {
      const topGamesObj = sidebarData.value.menu.find(a => a.menu_id === 3) ?? { list: [] }
      console.log(topGamesObj)
      return topGamesObj?.list?.map((sport) => {
        return {
          title: sport.sn,
          path: '',
          icon: sport.spic,
          useCloudImg: true,
          domId: `sports-hot-game-${sport.si}`,
          children: [
            { title: 'Outrights', path: getSportsRoutePath({ page: '/sport', si: `${sport.si}`, marketType: EPageDataMarketType.OUTRIGHT }), icon: 'spt-timing' },
            ...(sport.list
              ? sport.list.map((league) => {
                return {
                  title: league.cn,
                  icon: league.cpic,
                  useCloudImg: true,
                  path1: getSportsRoutePath({ page: '/sport', si: `${sport.si}`, ci: league.ci, pgid: league.pgid, cn: league.cn, icon: league.cpic }),
                }
              })
              : []),

            { title: 'View All', path: getSportsRoutePath({ page: '/sport', si: `${sport.si}` }), icon: 'uni-view-all2', separate: true },
          ],
        }
      })
    }
    return []
  })

  /** 体育项目 */
  const sportGameList = computed(() => {
    if (sidebarData.value && sidebarData.value.all) {
      const children = sidebarData.value.all.map((item) => {
        return {
          title: item.sn,
          path: getSportsRoutePath({ page: '/sport', si: `${item.si}` }),
          icon: item.spic,
          useCloudImg: true,
        }
      })
      return [
        {
          title: t('sports_events2'),
          path: '',
          icon: 'uni-view-all2',
          children,
          domId: 'sports-game-list',
        },
      ]
    }
    return []
  })

  /** 热门导航 */
  const hotEventNavs = computed(() => {
    if (allSportsCount.value) {
      return allSportsCount.value.list.filter(a => a.ohc > 0).map((b) => {
        return {
          ...b,
          icon: b.spic,
          label: b.sn,
          value: b.si,
          useCloudImg: true,
        }
      })
    }
    return []
  })

  /** 滚球导航 */
  const sportLiveNavs = computed(() => {
    if (allSportsCount.value) {
      return allSportsCount.value.list.filter(a => a.lc > 0).map((b) => {
        return {
          ...b,
          icon: b.spic,
          label: b.sn,
          value: b.si,
          useCloudImg: true,
        }
      })
    }
    return []
  })

  /** 早盘导航 */
  const earlyEventNavs = computed(() => {
    if (allSportsCount.value) {
      return allSportsCount.value.list.filter(a => a.ec > 0).map((b) => {
        return {
          ...b,
          icon: b.spic,
          label: b.sn,
          value: b.si,
          useCloudImg: true,
        }
      })
    }
    return []
  })

  /** 所有球种的si */
  const allSportsSi = computed(() => {
    if (sidebarData.value && sidebarData.value.all)
      return sidebarData.value.all.map(a => a.si)
    return []
  })

  /** 所有球种名称sid对应列表 */
  const allSportsNameList = computed(() => {
    if (sidebarData.value && sidebarData.value.all)
      return sidebarData.value.all
    return []
  })

  /** 赛事类型下拉选单 */
  const sportsEventTypeList = computed(() => {
    if (homePageConfig.value && homePageConfig.value.list_filter) {
      return homePageConfig.value.list_filter.map((a) => {
        return {
          label: a.name,
          value: a.lfid,
          ...a,
        }
      })
    }
    else if (homePageConfig.value && !homePageConfig.value.list_filter) {
      return null
    }
    return []
  })

  // /** 所有球种盘口类型下拉选单 */
  const sportsBetTypeList = computed(() => {
    if (homePageConfig.value && homePageConfig.value.bettype_filter) {
      return homePageConfig.value.bettype_filter.map((a) => {
        return {
          si: a.si,
          btl: a.btl.map((b) => {
            return {
              ...b, value: `${b.bt}@@${b.egi}`, label: b.btn,
            }
          }),
        }
      })
    }
    return []
  })

  /** 获取球种对应icon */
  function getSportsIconBySi(si: number) {
    return allSportsNameList.value.find(a => a.si === si)?.spic ?? ''
  }

  /** 获取球种对应名称 */
  function getSportsNameBySi(si: number) {
    return allSportsNameList.value.find(a => a.si === si)?.sn ?? ''
  }

  /** 切换场馆 */
  function changeProvider(id: string) {
    if (currentProvider.value === id)
      return

    if (numberReg.test(id)) {
      currentProvider.value = id
      Local.set(STORAGE_SPORTS_CURRENT_PROVIDER, id)
    }
  }

  /** 渲染赔率 */
  const renderOdds = (odds: number) => {
    return computed(() => {
      let _type = sportsOddsType.value
      if (getCurrentLanguageForBackend() === EnumLanguage['zh-CN'])
        _type = EnumSportsOddsType.DECIMAL

      return SportsOdds.convert(odds, _type).toString()
    })
  }

  /** 设置当前体育赔率展示方式 */
  function setSportsOddsType(type: EnumSportsOddsType) {
    sportsOddsType.value = type
    Local.set(STORAGE_SPORTS_ODDS_TYPE_KEY, type)
  }

  /** 获取当前体育赔率展示方式 */
  function getSportsOddsType() {
    const value = Local.get<EnumSportsOddsType>(STORAGE_SPORTS_ODDS_TYPE_KEY)?.value
    if (value)
      return value
    else
      return EnumSportsOddsType.DECIMAL
  }

  /** 更新收藏赛事列表 */
  function refreshSportsFavList() {
    runGetFavoriteList({
      si: 0,
      cur: currencyConfig[currentGlobalCurrency.value].cur,
    })
  }

  watch(router.currentRoute, () => {
    if (isRequestSportsLogin.value)
      runAsyncSportsLogin()
  })

  return {
    AllOddsTypes,
    sportsOddsType,
    betSlipData,
    currentProvider,
    allSportsCount,
    sidebarData,
    liveCount,
    currentHotNav,
    currentLiveNav,
    currentEarlyNav,
    currentVSportsNav,
    currentVSportsBetType,
    hotEventNavs,
    sportLiveNavs,
    earlyEventNavs,
    currentUpcomingNav,
    sportsFavoriteData,
    allSportsSi,
    allSportsNameList,
    cart,
    sportsBetTypeList,
    sportsEventTypeList,
    isSportsMaintained,
    isSportsLoginSusses,
    isOnSportsQuickBet,
    isShowAllSportsList,
    competitionListData,
    sportsMenu,
    sportHotGames,
    sportGameList,
    renderOdds,
    setSportsOddsType,
    getSportsOddsType,
    changeProvider,
    refreshSportsFavList,
    runSportsCount,
    getSportsIconBySi,
    getSportsNameBySi,
    runGetCompetitionListData,
    runAsyncGetCompetitionListData
  }
})

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useSportsStore, import.meta.hot))
